package fybug.nulll.pdstream.Source;
import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;

import java.util.LinkedList;
import java.util.NoSuchElementException;

import fybug.nulll.pdfunctionlibrary.Processing.Check;
import fybug.nulll.pdfunctionlibrary.Processing.ConsistentField;
import fybug.nulll.pdfunctionlibrary.Util.Processing.Arrarys;
/**
 * <h2>关闭容器.</h2>
 * <pre>
 * 用于批量关闭对象
 * 支持并发
 * 关闭后也可继续使用
 * </pre>
 *
 * @author fybug
 * @version 0.0.3
 * @see ConsistentField
 * @see AutoCloseable
 * @since JDK 1.8
 */
@SuppressWarnings( "all" )
public
class CloseAll extends ConsistentField implements AutoCloseable {
    /** <p>保存要关闭的对象.</p> */
    @NotNull final protected LinkedList<AutoCloseable> linkedList = new LinkedList<>();
    // 同步锁
    @NotNull final private Object listLock = new Object();

    /** <p>构造一个空的关闭容器.</p> */
    public
    CloseAll() {}

    /** <p>构造关闭容器并添加要关闭的对象.</p> */
    public
    CloseAll(@Nullable final AutoCloseable... close) { appendClose(close); }

    @Override
    protected
    boolean consistent(@NotNull final Object o)
    { return Check.equalsFidle(linkedList, ((CloseAll) o).linkedList); }

    /** <p>添加要关闭的对象.</p> */
    @NotNull
    public
    CloseAll appendClose(@Nullable final AutoCloseable... close) {
        Arrarys.conversionArrayType(close, (v) -> {
            synchronized ( listLock ){
                linkedList.add(v);
            }
            return null;
        }, AutoCloseable[].class);
        return this;
    }

    /** <p>关闭该类下的所有可关闭对象.</p> */
    @Override
    public
    void close() {
        @NotNull AutoCloseable closeable;
        try {
            synchronized ( listLock ){
                while( true ){
                    closeable = linkedList.removeFirst();
                    try {
                        closeable.close();
                    } catch ( Exception ignored ) {
                    }
                }
            }
        } catch ( NoSuchElementException ignored ) {
        }
    }
}
